
google.load("maps", "2");

    var map;
    var geocoder;
    var address;


// Call this function when the page has been loaded
function initialize() {
  map = new google.maps.Map2(document.getElementById('address'));
  map.setUIToDefault();
  map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 1);
  geocoder = new google.maps.ClientGeocoder();
  google.maps.Event.addListener(map, "click", getAddress);
}

function getAddress(overlay, latlng) {
      if (latlng != null) {
        address = latlng;
        geocoder.getLocations(latlng, showAddress1);
      }
    }

function showAddress1(response) {
   map.clearOverlays();
   if (!response || response.Status.code != 200) {
     alert("Status Code:" + response.Status.code);
   } else {
     place = response.Placemark[0];
     point = new google.maps.LatLng(place.Point.coordinates[1],
                         place.Point.coordinates[0]);
     // Json Revere Geocondig
     $.getJSON('/json/reverse_search_address/'+place.Point.coordinates[1]+'/'+place.Point.coordinates[0],
     	function(data){
			var jsonData = data;
			var toclean = [ 'country_name_code' ,
	        'country_name' ,
	        'administrative_area_name' ,
	        'sub_administrative_area_name' ,
	        'locality_name' ,
	        'thoroughfare_name',
	        'google_address',
	        'postal_code_number',
	        'google_lng',
	        'google_lat'];
	    	for (var key in toclean ){
	    		var tag = "#"+toclean[key];
				$(tag).val('');
		 		};
		 	$('#google_address_legend').html(jsonData['google_address']);
			for (var key in jsonData) {

				var value = jsonData[key];
				var tag = "#"+key;
				$(tag).val(value);
			 	}
			 })
     marker = new google.maps.Marker(point);
     map.addOverlay(marker);
     marker.openInfoWindowHtml(
     '<b>orig latlng:</b>' + response.name + '<br/>' +
     '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
     '<b>Status Code:</b>' + response.Status.code + '<br>' +
     '<b>Status Request:</b>' + response.Status.request + '<br>' +
     '<b>Address:</b>' + place.address + '<br>' +
     '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
     '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
     $('#search_address').val(place.address);
   }
 }

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
  		//var map = new google.maps.Map2(document.getElementById('address'));
  		//map.setUIToDefault();
          self.map.setCenter(point, 11);
          var marker = new google.maps.Marker(point, {draggable: true});
          self.map.addOverlay(marker);
   		  google.maps.Event.trigger(marker, "click");
        }
      }
    );
  }
}

google.setOnLoadCallback(initialize);
